<template>
  <div class="store-manage">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="title">商家管理</span>
          <div class="header-actions">
            <el-select
              v-model="statusFilter"
              placeholder="筛选状态"
              clearable
              style="width: 150px; margin-right: 10px"
              @change="handleSearch">
              <el-option label="待审核" :value="0" />
              <el-option label="已通过" :value="1" />
              <el-option label="已拒绝" :value="2" />
            </el-select>
            <el-input
              v-model="searchKeyword"
              placeholder="搜索商家名称"
              style="width: 250px"
              clearable
              @clear="handleSearch"
              @keyup.enter="handleSearch">
              <template #append>
                <el-button :icon="Search" @click="handleSearch" />
              </template>
            </el-input>
          </div>
        </div>
      </template>

      <!-- 商家列表表格 -->
      <el-table :data="storeList" v-loading="loading" stripe>
        <el-table-column prop="id" label="商家ID" width="80" />
        <el-table-column prop="store_name" label="商家名称" width="180" />
        <el-table-column prop="user_name" label="店主" width="120" />
        <el-table-column prop="phone" label="联系电话" width="130" />
        <el-table-column prop="address" label="地址" min-width="200" show-overflow-tooltip />
        <el-table-column prop="state" label="状态" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.state === 0" type="warning">待审核</el-tag>
            <el-tag v-else-if="row.state === 1" type="success">已通过</el-tag>
            <el-tag v-else type="danger">已拒绝</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="260" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="row.state === 0"
              type="success"
              size="small"
              @click="handleReview(row, 1)">
              通过
            </el-button>
            <el-button
              v-if="row.state === 0"
              type="danger"
              size="small"
              @click="handleReview(row, 2)">
              拒绝
            </el-button>
            <el-button
              v-if="row.state !== 0"
              type="info"
              size="small"
              disabled>
              {{ row.state === 1 ? '已通过' : '已拒绝' }}
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next"
        @size-change="fetchStores"
        @current-change="fetchStores"
        style="margin-top: 20px; justify-content: center"
      />
    </el-card>

    <!-- 拒绝原因对话框 -->
    <el-dialog v-model="rejectDialogVisible" title="拒绝原因" width="500px">
      <el-form :model="rejectForm" label-width="100px">
        <el-form-item label="商家名称">
          <span>{{ rejectForm.storeName }}</span>
        </el-form-item>
        <el-form-item label="拒绝原因" required>
          <el-input
            v-model="rejectForm.reason"
            type="textarea"
            :rows="4"
            placeholder="请输入拒绝原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="rejectDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmReject">确认拒绝</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { adminApis } from '@/assets/apis/AdminApis'

// 数据
const loading = ref(false)
const storeList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchKeyword = ref('')
const statusFilter = ref('')

// 拒绝对话框
const rejectDialogVisible = ref(false)
const rejectForm = ref({
  storeId: 0,
  storeName: '',
  reason: ''
})

// 获取商家列表
const fetchStores = async () => {
  loading.value = true
  try {
    const data = await adminApis.getStores(
      currentPage.value,
      pageSize.value,
      searchKeyword.value,
      statusFilter.value
    )
    storeList.value = data.stores
    total.value = data.total
  } catch (error: any) {
    console.error('获取商家列表失败：', error)
    ElMessage.error(error.error || '获取商家列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchStores()
}

// 审核商家
const handleReview = async (row: any, status: number) => {
  if (status === 1) {
    // 通过
    ElMessageBox.confirm('确认通过该商家的申请吗？', '确认操作', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'success'
    }).then(async () => {
      try {
        await adminApis.reviewStore(row.id, status, '')
        ElMessage.success('审核通过')
        fetchStores()
      } catch (error: any) {
        console.error('审核失败：', error)
        ElMessage.error(error.error || '审核失败')
      }
    }).catch(() => {})
  } else {
    // 拒绝
    rejectForm.value = {
      storeId: row.id,
      storeName: row.store_name,
      reason: ''
    }
    rejectDialogVisible.value = true
  }
}

// 确认拒绝
const confirmReject = async () => {
  if (!rejectForm.value.reason.trim()) {
    ElMessage.warning('请输入拒绝原因')
    return
  }

  try {
    await adminApis.reviewStore(
      rejectForm.value.storeId,
      2,
      rejectForm.value.reason
    )
    ElMessage.success('已拒绝该申请')
    rejectDialogVisible.value = false
    fetchStores()
  } catch (error: any) {
    console.error('审核失败：', error)
    ElMessage.error(error.error || '审核失败')
  }
}

// 删除商家
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `确定删除商家"${row.store_name}"吗？删除后将无法恢复！`,
    '警告',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await adminApis.deleteStore(row.id)
      ElMessage.success('商家删除成功')
      fetchStores()
    } catch (error: any) {
      console.error('删除商家失败：', error)
      ElMessage.error(error.error || '删除失败')
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 初始化
onMounted(() => {
  fetchStores()
})
</script>

<style scoped>
.store-manage {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
}
</style>

